const api = require("../../utils/api"); // ✅ 确保 `api.js` 被正确导入

Page({
  data: {
    username: "未登录",
    avatar: "/assets/images/avatar.png" // ✅ 默认头像
  },

  onShow() { 
    const username = wx.getStorageSync("username");
    const avatar = wx.getStorageSync("avatar"); // ✅ 读取头像
    console.log("当前存储的 username:", username);
    console.log("当前存储的 avatar:", avatar); // ✅ 调试点
    if (!avatar || avatar === "") {
        avatar = "/assets/images/avatar.png"; // 如果没有头像，使用默认头像
      }
      this.setData({
        username: username || "未登录",
        avatar: avatar
      });
      wx.setStorageSync("avatar", avatar); // 确保全局存储
    },



  // ✅ 新增方法：跳转到 "编辑个人信息" 页面
  editProfile() {
    wx.navigateTo({ url: "/pages/my/editProfile/editProfile" });
  },

  myChildren() {
    wx.navigateTo({ url: "/pages/my/childrenList/childrenList" });
  },
  
 // ✅ 新增方法：跳转到人工客服（Chat）页面
  openChat() {
    wx.navigateTo({ url: "/pages/my/chat/chat" });
  },
  
  logout() {
    wx.showModal({
      title: "退出登录",
      content: "退出后聊天记录将被清除，确定要退出吗？",
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync("token");
          wx.removeStorageSync("username");
          wx.removeStorageSync("avatar"); 
          wx.removeStorageSync("chatHistory"); // ✅ 清除聊天记录

          // ✅ 触发聊天页面的刷新，让聊天数据清空
          const pages = getCurrentPages();
          pages.forEach(page => {
            if (page.route === "pages/my/chat/chat") {
              page.setData({ messages: [] });
            }
          });

          wx.showToast({ title: "已退出", icon: "success" });
          wx.redirectTo({ url: "/pages/login/login" });
        }
      }
    });
}
});
